from pygrabber.dshow_graph import FilterGraph
import cv2
import time


graph = FilterGraph()
devices = graph.get_input_devices()
target_camera = "USB Camera"  # 替换为你的摄像头名称

start = time.time()
if target_camera in devices:
    index = devices.index(target_camera)
    cap = cv2.VideoCapture(index, cv2.CAP_DSHOW)
    print(f"初始化耗时: {time.time() - start:.2f}s")
else:
    print("未找到指定摄像头！")
    exit()

if not cap.isOpened():
    print("无法打开摄像头")
    exit()


start = time.time()

cap.set(cv2.CAP_PROP_FRAME_WIDTH, 3840) # 设置分辨率
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 1080)
cap.set(cv2.CAP_PROP_FOURCC, cv2.VideoWriter_fourcc('M','J','P','G')) # 跳过协议协商，加速

prev_time = 0
fps = 0

while True:
    # 读取一帧
    ret, frame = cap.read()
    if not ret:
        print("无法读取帧！")
        break

    # 计算 FPS（当前时间与上一帧时间差）
    current_time = time.time()
    time_diff = current_time - prev_time
    if time_diff > 0:
        fps = 1 / time_diff
    prev_time = current_time

    # 在画面上显示 FPS（左上角）
    fps_text = f"FPS: {fps:.1f}"
    cv2.putText(frame, fps_text, (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 
                1, (0, 255, 0), 2, cv2.LINE_AA)

    # 显示画面
    cv2.imshow('Camera with FPS', frame)

    # 按 'q' 键退出
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# 释放资源
cap.release()
cv2.destroyAllWindows()